package com.anjiplus.template.gaea.business.GeneralToolService.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;

import com.anjiplus.template.gaea.business.GeneralToolService.GsLogService;
import org.example.quartz.service.LogService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class GsLogServiceImpl implements GsLogService {
    @Value(value = "${spring.datasource.GSYY}")
    private String GSYY;

    /**
     * 调用:核算部门、行政部门
     *
     * @param data       json数据
     * @param methodName 方法名
     */
    @Override
    public void instLog(String data, String methodName) {
        if (!data.isEmpty()) {
            //LogService日志接口
            LogService loginfo = SpringUtil.getBean(LogService.class);
            JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);
            //转为JSONObject
            JSONObject jsonObject = JSONObject.parseObject(data);
            //获取返回参数
            String returnMSG = jsonObject.getString("result").replace("'", "\\\\''");
            //url
            String gsUrl = jsonObject.getString("apiUrl");
            //发送参数
            String GsxzJson = jsonObject.getString("requestData");
            //转为JSONObject
            JSONObject fsJson = JSONObject.parseObject(GsxzJson);
            //TS时间
            String TS = fsJson.getString("TS");
            //YYid
            String yyid = fsJson.getString("YYID");
            if (returnMSG.contains("code=0")) {
                int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "成功", GsxzJson, returnMSG, "", yyid, gsUrl, TS);
                if (loginsert > 0) {
                    System.out.println("日志写入成功！！");
                } else {
                    System.out.println("日志写入失败！！");
                }
            } else if (returnMSG.contains("code=1")) {
                //写入日志表
                int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "失败", GsxzJson, returnMSG, "", yyid, gsUrl, TS);
                if (loginsert > 0) {
                    System.out.println("日志写入成功！！");
                } else {
                    System.out.println("日志写入失败！！");
                }
            } else {
                //写入日志表
                int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常", GsxzJson, returnMSG, "", yyid, gsUrl, TS);
                if (loginsert > 0) {
                    System.out.println("日志写入成功！！");
                } else {
                    System.out.println("日志写入失败！！");
                }
            }
        }
    }

    /**
     * 添加日志
     *
     * @param
     * @throws
     */
    @Override
    public int loginfo(JdbcTemplate jdbcTemplate, String methodName, String ts, String state, String inJson, String outJson, String dateid, String yyid, String gsUrl, String TS) {
        String logInsert = "INSERT INTO " + GSYY + ".gs_yy_log(ID,methodName,\n" +
                " ts, state, inJson, outJson, dateid, yyid, gsUrl ,yyts) VALUES " +
                "(SYS_GUID(),'" + methodName + "',SYSDATE,'" + state + "'," +
                "'" + inJson + "'," +
                "'" + outJson + "'," +
                "'" + dateid + "'," +
                "'" + yyid + "'," +
                "'" + gsUrl + "'," +
                "to_date('" + TS + "', 'yyyy-mm-dd hh24:mi:ss'))";
        System.out.println("日志sql" + logInsert);
        int loginsert = jdbcTemplate.update(logInsert);
        return loginsert;
    }

    /**
     * 添加日志-非函数字段（CLOB）
     *
     * @param
     * @throws
     */
    @Override
    public int loginfoItem(JdbcTemplate jdbcTemplate, String methodName, String ts, String state, Integer num, String inJson, String outJson, String dateid, String yyid, String gsUrl, String TS) {
        String logInsert = "INSERT INTO " + GSYY + ".gs_yy_log(ID,methodName, ts, state, num,inJson, outJson, dateid, yyid, gsUrl ,yyts) " +
                "VALUES " +
                "(SYS_GUID(),'" + methodName + "', SYSDATE, '" + state + "', '" + num + "', '" + inJson + "', '" + outJson + "', '" + dateid + "','" + yyid + "','" + gsUrl + "',to_date('" + TS + "', 'yyyy-mm-dd hh24:mi:ss'))";
        int loginsert = jdbcTemplate.update(logInsert);
        return loginsert;
    }

    /**
     * 添加日志-函数字段（CLOB）
     *
     * @param
     * @throws
     */
    @Override
    public int loginfoClob(JdbcTemplate jdbcTemplate, String methodName, String ts, String state, String inJson, String outJson, String dateid, String yyid, String gsUrl, String TS) {
        String toClob = "";
        String[] injson = strToStrArray(inJson, 3000);
        for (int i = 0; i < injson.length; i++) {
            toClob += "TO_CLOB('" + injson[i] + "')||";
        }
        toClob += "TO_CLOB('')";

        String toClob1 = "";
        String[] outjson = strToStrArray(outJson, 3000);
        for (int i = 0; i < outjson.length; i++) {
            toClob1 += "TO_CLOB('" + outjson[i] + "')||";
        }
        toClob1 += "TO_CLOB('')";


        String yyidStr = "";
        if (StrUtil.isNotBlank(yyid)) {
            String[] yyidjson = strToStrArray(yyid, 2000);
            for (int i = 0; i < yyidjson.length; i++) {
                yyidStr += "TO_CLOB('" + yyidjson[i] + "')||";
            }
            yyidStr += "TO_CLOB('')";
        }

        String logInsert = "INSERT INTO " + GSYY + ".gs_yy_log(ID,methodName,\n" +
                " ts, state, inJson, outJson, dateid, yyid, gsUrl ,yyts) VALUES " +
                "(SYS_GUID(),'" + methodName + "',SYSDATE,'" + state + "'," + toClob + "," + toClob1 + "," +
                "'" + dateid + "'," +
                "" + yyidStr + "," +
                "'" + gsUrl + "'," +
                "to_date('" + TS + "', 'yyyy-mm-dd hh24:mi:ss'))";

        if (StrUtil.isBlank(yyid)) {
            logInsert = "INSERT INTO " + GSYY + ".gs_yy_log(ID,methodName,\n" +
                    " ts, state, inJson, outJson, dateid, yyid, gsUrl ,yyts) VALUES " +
                    "(SYS_GUID(),'" + methodName + "',SYSDATE,'" + state + "'," + toClob + "," + toClob1 + "," +
                    "'" + dateid + "'," +
                    "'" + yyidStr + "'," +
                    "'" + gsUrl + "'," +
                    "to_date('" + TS + "', 'yyyy-mm-dd hh24:mi:ss'))";
        }
        int loginsert = jdbcTemplate.update(logInsert);
        return loginsert;
    }

    /*
     * 将字符串按照指定长度分割成字符串数组
     * @return
     */
    public String[] strToStrArray(String src, int length) {
        //检查参数是否合法
        if (null == src || src.equals("")) {
            return null;
        }
        if (length <= 0) {
            return null;
        }

        //获取整个字符串可以被切割成字符子串的个数
        int n = (src.length() + length - 1) / length;
        String[] split = new String[n];
        for (int i = 0; i < n; i++) {
            if (i < (n - 1)) {
                split[i] = src.substring(i * length, (i + 1) * length);
            } else {
                split[i] = src.substring(i * length);
            }
        }
        return split;
    }
}
